#include "glutils.h"

#include <cstdio>
#include <iostream>
#include <QDebug>

using namespace std;

GLUtils::GLUtils() {}

int GLUtils::checkForOpenGLError(const char * file, int line) {
    //
    // Returns 1 if an OpenGL error occurred, 0 otherwise.
    //
    GLenum glErr;
    int    retCode = 0;

    glErr = glGetError();
    while (glErr != GL_NO_ERROR)
    {
        printf("glError in file %s @ line %d: %s\n", file, line, gluErrorString(glErr));
        retCode = 1;
        glErr = glGetError();
    }
    return retCode;

}

void GLUtils::dumpGLInfo(bool dumpExtensions) {
    const GLubyte *renderer = glGetString( GL_RENDERER );
    const GLubyte *vendor = glGetString( GL_VENDOR );
    const GLubyte *version = glGetString( GL_VERSION );
    const GLubyte *glslVersion = glGetString( GL_SHADING_LANGUAGE_VERSION );

    GLint major, minor;
    glGetIntegerv(GL_MAJOR_VERSION, &major);
    glGetIntegerv(GL_MINOR_VERSION, &minor);

    qDebug() <<"GL Vendor    :" << (const char*)vendor;
    qDebug() <<"GL Renderer  :" << (const char*)renderer;
    qDebug() <<"GL Version   :" << (const char*)version;
    qDebug() <<"GL Version   :" << major << minor;
    qDebug() <<"GLSL Version :" << (const char*)glslVersion;

    if( dumpExtensions ) {
        GLint nExtensions;
        glGetIntegerv(GL_NUM_EXTENSIONS, &nExtensions);
        for( int i = 0; i < nExtensions; i++ ) {
            printf("%s\n", glGetStringi(GL_EXTENSIONS, i));
        }
    }
}

int GLUtils::CheckGLError(char *file, int line)
{
    GLenum glErr;
    int    retCode = 0;

    glErr = glGetError();
    while (glErr != GL_NO_ERROR)
    {
      const GLubyte* sError = gluErrorString(glErr);

      if (sError)
        qDebug() << "GL Error #" << glErr << "(" << gluErrorString(glErr) << ") " << " in File " << file << " at line: " << line << endl;
      else
        qDebug() << "GL Error #" << glErr << " (no message available)" << " in File " << file << " at line: " << line << endl;

      retCode = 1;
      glErr = glGetError();
    }
    return retCode;
}
